import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

export default async function handler(req, res) {
  const { method } = req;

  if (method === "GET") {
    const { id } = req.query;
    if (id) {
      try {
        const role = await prisma.role.findUnique({
          where: { id: parseInt(id) },
          include: { permissions: true }, // Include associated permissions
        });

        if (!role) {
          return res.status(404).json({ error: "角色未找到" });
        }
        return res.status(200).json(role);
      } catch (error) {
        console.log("error --- ", error);
        return res.status(500).json({ error: "获取角色失败" });
      }
    } else {
      // Query all roles
      const roles = await prisma.role.findMany({
        include: { permissions: true }, // Include associated permissions
      });
      return res.status(200).json(roles);
    }
  }

  if (method === "POST") {
    // Create a new role
    const { name, permissions } = req.body; // Expecting permissions to be an array of permission IDs
    try {
      const newRole = await prisma.role.create({
        data: {
          name,
          permissions: {
            create: permissions.map((permissionId) => ({ permissionId })), // Associate permissions
          },
        },
      });
      return res.status(201).json(newRole);
    } catch (error) {
      console.log("error --- ", error);
      return res.status(500).json({ error: "创建角色失败" });
    }
  }

  if (method === "PUT") {
    const { id } = req.query;
    // Update role
    if (!id) {
      return res.status(400).json({ error: "缺少角色 ID" });
    }
    const { name, permissions } = req.body; // Expecting permissions to be an array of permission IDs
    try {
      const updatedRole = await prisma.role.update({
        where: { id: parseInt(id) },
        data: {
          name,
          permissions: {
            deleteMany: {}, // Clear existing permissions
            create: permissions.map((permissionId) => ({ permissionId })), // Add new permissions
          },
        },
      });
      return res.status(200).json(updatedRole);
    } catch (error) {
      console.log("error --- ", error);
      return res.status(500).json({ error: "更新角色失败" });
    }
  }

  if (method === "DELETE") {
    const { id } = req.query;
    // Delete role
    if (!id) {
      return res.status(400).json({ error: "缺少角色 ID" });
    }
    try {
      await prisma.role.delete({
        where: { id: parseInt(id) },
      });
      return res.status(204).end(); // No Content
    } catch (error) {
      console.log("error --- ", error);
      return res.status(500).json({ error: "删除角色失败" });
    }
  }

  // Handle unsupported methods
  res.setHeader("Allow", ["GET", "POST", "PUT", "DELETE"]);
  res.status(405).end(`Method ${method} Not Allowed`);
}
